package com.guagua.system.strategy.impl;

import com.guagua.system.entity.UploadConfig;
import com.guagua.system.strategy.UploadStrategy;
import io.minio.*;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

@Component("MINIO")
public class MinioUploadStrategy implements UploadStrategy {
    private final MinioClient minioClient;
    private final UploadConfig config;
    
    public MinioUploadStrategy(UploadConfig config) {
        this.config = config;
        this.minioClient = MinioClient.builder()
                .endpoint(config.getMinioEndpoint())
                .credentials(config.getMinioAccessKey(), config.getMinioSecretKey())
                .build();
    }
    
    @Override
    public String upload(MultipartFile file) {
        try {
            String fileName = UUID.randomUUID() + getFileExtension(file);
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(config.getMinioBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            return config.getMinioEndpoint() + "/" + config.getMinioBucketName() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("文件上传到MinIO失败", e);
        }
    }
    
    @Override
    public void delete(String fileUrl) {
        try {
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(config.getMinioBucketName())
                    .object(fileName)
                    .build());
        } catch (Exception e) {
            throw new RuntimeException("从MinIO删除文件失败", e);
        }
    }
    
    private String getFileExtension(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
    }
} 